package two.chapter_4.c4_4;

import edu.princeton.cs.algs4.In;
import two.chapter_1.c1_3.Bag;
import two.chapter_4.c4_4.DirectedEdge;

/**
 * 加权有向图
 */
public class EdgeWeightedDigraph {

    private int v;//顶点数
    private int e;//边数
    private Bag<DirectedEdge>[] adj;
    public EdgeWeightedDigraph(int v){
        this.v=v;
        this.e=0;
        adj=new Bag[v];
        for (int i=0;i<v;i++){
            adj[i]=new Bag<>();
        }
    }
    public EdgeWeightedDigraph(In in){
        this(in.readInt());
        int e=in.readInt();
        for (int i=0;i<e;i++){
            int v=in.readInt();
            int w=in.readInt();
            double weight=in.readDouble();
            DirectedEdge edge=new DirectedEdge(v,w,weight);
            addEdge(edge);
        }
    }
    public int v() {
        return v;
    }

    public int e() {
        return e;
    }

    /**
     * 向图中添加一条边
     * @param e
     */
    public void addEdge(DirectedEdge e) {
        adj[e.from()].add(e);
        this.e++;
    }

    /**
     * 和v相关联的所有边
     * @param v
     * @return
     */
    public Iterable<DirectedEdge> adj(int v) {
        return adj[v];
    }

    /**
     * 图的所有边
     * @return
     */
    public Iterable<DirectedEdge> edges() {
        Bag<DirectedEdge> edges=new Bag<>();
        for (int i=0;i<v;i++){
            for (DirectedEdge edge:adj(i)){
                edges.add(edge);
            }
        }
        return edges;
    }
}
